package control;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Marca;
import bean.Pais;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

import dao.DAOFactory;
import dao.Entidad;

/**
 * Servlet implementation class ServletPais
 */
@WebServlet("/ServletPais")
public class ServletPais extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletPais() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		if(request.getParameter("action")!=null){
			//List<Pais> listAll
			String action=(String)request.getParameter("action");
			List<Pais> listPais= new ArrayList<Pais>();
			//Gson gson = new Gson();
			response.setContentType("application/json");
			DAOFactory factory=DAOFactory.getFactoryConcrete(DAOFactory.MYSQL);
			Entidad<Pais> pais= factory.getPaisDAO();
			System.out.print("Pais");
			
			if(action.equals("llenarcombo")){
				try{
					
					listPais = pais.listAll();		
					String listData="[";
					for(Pais i: listPais){
				           listData = listData + "{\"DisplayText\":\""+i.getNomb_Pais()+"\",\"Value\":\""+i.getId_Pais()+"\"},";
					}
					listData = listData.substring(0, listData.length()-1);
					listData = listData +"]";
					listData="{\"Result\":\"OK\",\"Options\":"+listData+"}";					
					
					response.setHeader("Cache-control", "no-cache, no-store");
			        response.setHeader("Pragma", "no-cache");
			        response.setHeader("Expires", "-1");
					response.getWriter().print(listData);
					System.out.println(listData);
					
				}catch(Exception ex){
					String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace()+"}";
					response.getWriter().print(error);
					System.out.println(error);
				}
				
			}else if(action.equals("create") || action.equals("update")){
			  
			}   
			
			
			}
		}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	
}
